package com.zoe.onelink.auth.token.authenticate;

import cn.hutool.core.util.StrUtil;
import com.zoe.onelink.auth.token.processor.OnelinkTokenInfoProcessor;
import com.zoe.onelink.common.constant.OnelinkConstant;
import com.zoe.onelink.common.enumeration.ExceptionCode;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-05-12
 */
@RequiredArgsConstructor
@Slf4j
public class OnelinkTokenAuthenticate {

    private final OnelinkTokenInfoProcessor onelinkTokenInfoProcessor;
    private final List<OnelinkTokenAuthenticateCallback> callbacks;
    private final HttpServletRequest request;

    public ExceptionCode authenticate(String onelinkToken) {
        // Token为空
        if (StrUtil.isBlank(onelinkToken)) {
            return ExceptionCodeEnum.TOKEN_NOT_NULL;
        }

        ExceptionCode exceptionCode = null;
        try {
            Map<String, Object> authMap = this.onelinkTokenInfoProcessor.process(onelinkToken);
            callbacks.forEach(callback -> callback.onAuthenticateSuccess(authMap));
        } catch (ApiException apiException) {
            exceptionCode = apiException.getExceptionCode();
        } catch (Exception e) {
            callbacks.forEach(callback -> callback.onAuthenticateFailure(e));
            request.setAttribute(OnelinkConstant.ATTR_TOKEN_AUTHENTICATE_FAILURE, e.getMessage());
            exceptionCode = ExceptionCodeEnum.BIZ_ERROR;
        }
        return exceptionCode;
    }

}
